﻿using System;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.Mvc;
using System.Collections.Generic;
using System.Text;
using System.Threading;
using System.Configuration;
using System.Data.Linq;
using System.Reflection;
namespace Longtop.Web.Comm {
    public static class LocalizationHelpers {

        public static string LanguageFolder {
            get {
                if (ConfigurationManager.AppSettings["LanguageFolder"] == null)
                    return "Language\\";
                else
                    return ConfigurationManager.AppSettings["LanguageFolder"] + "\\";

            }
        }

        /// <summary>
        ///  For mvc view 
        /// </summary>
        /// <param name="htmlhelper"></param>
        /// <param name="key"></param>
        /// <returns></returns>
        public static string Local(this HtmlHelper htmlhelper, string key) {
            string FilePath = htmlhelper.ViewContext.HttpContext.Server.MapPath("~/" + LanguageFolder);
            return GetLangString(htmlhelper.ViewContext.HttpContext, key, FilePath);
        }


        /// <summary>
        /// For webfrom view
        /// </summary>
        /// <param name="htmlhelper"></param>
        /// <param name="key"></param>
        /// <returns></returns>
        public static string Local(this TemplateControl view, string key) {
            string FilePath = HttpContext.Current.Server.MapPath("/") + LanguageFolder;
            return GetLangString(HttpContext.Current, key, FilePath);
        }

        /// <summary>
        /// Out the javascript variable it like "var key='enString';"
        /// </summary>
        /// <param name="htmlhelper"></param>
        /// <param name="key"></param>
        /// <returns></returns>
        public static string LocalOutJsVar(this HtmlHelper htmlhelper, string key) {
            string FilePath = htmlhelper.ViewContext.HttpContext.Server.MapPath("/") + LanguageFolder;
            string langstr = GetLangString(htmlhelper.ViewContext.HttpContext, key, FilePath);
            return string.Format("var {0} = '{1}';", key, langstr);
        }
        /// <summary>
        /// for mvc Controller
        /// </summary>
        /// <param name="httpContext"></param>
        /// <param name="key"></param>
        /// <returns></returns>
        public static string InnerLocal(this HttpContextBase httpContext, string key) {
            string FilePath = httpContext.Server.MapPath("/") + LanguageFolder;
            return GetLangString(httpContext, key, FilePath);
        }

        private static string GetLangString(IServiceProvider httpContext, string key, string FilePath) {
            return LangResourceFileProvider.GetLangString(key, FilePath);
        }

        internal static IEnumerable<TEntity> Local<TEntity>(this Table<TEntity> table)
            where TEntity : class {
            var mainTableName = table.Context.Mapping.GetTable(typeof(TEntity)).TableName.Split('_')[0];
            var tableName = string.Format("{0}_{1}", mainTableName, Thread.CurrentThread.CurrentUICulture.Name.Replace('-', '_'));
            return table.Context.ExecuteQuery<TEntity>(string.Format("SELECT * FROM {0} culture inner join {1} mainEntity ON culture.{1}Id=mainEntity.{1}Id ", tableName, mainTableName.Split('.')[1])).AsQueryable();
        }

        //internal static IEnumerable<TEntity> Local<TEntity>(this Table<TEntity> table, Order[] orders, params ICriterion[] criteria)
        //    where TEntity : class {

        //    var query = table as IQueryable<TEntity>;
        //    QueryBuilder builder = new QueryBuilder();

        //    var talbeName = table.Context.Mapping.GetTable(typeof(TEntity)).TableName;

        //    var mainTableName = talbeName.Split('_')[0];
        //    // the tableName mapping to database
        //    var tableName = mainTableName + "_" + Thread.CurrentThread.CurrentUICulture.Name.Replace('-', '_');


        //    ConditionBuilder conditionBuilder = new ConditionBuilder();
        //    conditionBuilder.Build(predicate.Body);
        //    StringBuilder sb = new StringBuilder();
        //    var mainTableNameWithOutOwner = mainTableName.Split('.')[1];
        //    var primaryKey = mainTableNameWithOutOwner + "Id";
        //    sb.AppendFormat(string.Format("SELECT * FROM {0} culture inner join {1} mainEntity ON culture.{2}=mainEntity.{2} ", tableName, mainTableName, primaryKey));
        //    if (!String.IsNullOrEmpty(conditionBuilder.Condition)) {
        //        sb.Append(" WHERE " + conditionBuilder.Condition.Replace(string.Format("[{0}]", primaryKey), "mainEntity." + primaryKey));
        //    }
        //    return table.Context.ExecuteQuery<TEntity>(sb.ToString(), conditionBuilder.Arguments).AsQueryable();
        //}

    }
    public static class LangResourceFileProvider {
        public static string GetLangString(string Key, string FilePath) {
            string filename = Thread.CurrentThread.CurrentUICulture.Name + ".resources";

            System.Resources.ResourceReader reader = new System.Resources.ResourceReader(FilePath + filename);

            string resourcetype;
            byte[] resourcedata;
            string result = string.Empty;

            try {
                reader.GetResourceData(Key, out resourcetype, out resourcedata);
                //去掉第一个字节，无用
                byte[] arr = new byte[resourcedata.Length - 1];
                for (int i = 0; i < arr.Length; i++) {
                    arr[i] = resourcedata[i + 1];
                }
                result = System.Text.Encoding.UTF8.GetString(arr);

            }
            catch (Exception ex) {

            }
            finally {
                reader.Close();
            }

            return result;
        }
    }
}
